package cn.school.controller.workmgr;

import cn.hutool.core.util.StrUtil;
import cn.school.basics.service.BaseSpaceLocationService;
import cn.school.basics.vo.BaseSpaceLocationVO;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.SysUserUtils;
import cn.school.educational.entity.TeachingMaterialCollect;
import cn.school.workmgr.entity.HygieneDormitory;
import cn.school.workmgr.entity.HygieneDormitoryStatistics;
import cn.school.workmgr.service.HygieneDormitoryService;
import cn.school.workmgr.service.HygieneDormitoryStatisticsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @className: HygieneDormitoryController
 * @author: fangjin.tao
 * @date: 2022/12/9
 **/
@RestController
@Api(tags = "HygieneShcoolController => 宿舍卫生管理")
@RequestMapping("/workmgr/HygieneDormitory")
public class HygieneDormitoryController {
    @Autowired
    private HygieneDormitoryService hygieneDormitoryService;
    @Autowired
    private BaseSpaceLocationService baseSpaceLocationService;
	@Resource
	private HygieneDormitoryStatisticsService hygieneDormitoryStatisticsService;

    @ApiOperation("【宿舍卫生登记】获取列表")
    @GetMapping("/list")
    public CommonResult<CommonPage<HygieneDormitory>> list(@RequestParam Map<String, Object> params) {
        // 查询
        IPage<HygieneDormitory> iPage = this.hygieneDormitoryService.pageSql(params);

        return CommonResult.success(CommonPage.restPage(iPage));
    }

    @ApiOperation("【宿舍卫生登记】获取详情")
    @GetMapping("/info/{id}")
    public CommonResult<HygieneDormitory> getInfoById(@PathVariable Long id) {
        HygieneDormitory hygieneShcool = this.hygieneDormitoryService.getById(id);
        if (hygieneShcool == null) {
            throw new ApiException("领用记录不存在，请刷新页面");
        }
        return CommonResult.success(hygieneShcool);
    }

    @ApiOperation("【宿舍卫生登记】添加")
    @PostMapping("/addOrUpdate")
    @Transactional
    public CommonResult<HygieneDormitory> add(@RequestBody HygieneDormitory hygieneDormitory) {
        boolean isAddSuccess = false;

        // 宿舍
        BaseSpaceLocationVO dormitory = baseSpaceLocationService.getById(hygieneDormitory.getDormId());
        if (dormitory == null) {
            throw new ApiException("选择的宿舍不存在");
        } else {
            hygieneDormitory.setDormName(dormitory.getLocationName());
        }

        if (hygieneDormitory.getId() == null) {
            if (StrUtil.isNotEmpty(SysUserUtils.getSysUser().getSysuName())) {
                hygieneDormitory.setCreateByName(SysUserUtils.getSysUser().getSysuName());
            } else {
                hygieneDormitory.setCreateByName(SysUserUtils.getSysUser().getUsername());
            }
            hygieneDormitory.setCreateTime(Calendar.getInstance().getTime());
            hygieneDormitory.setModifyTime(Calendar.getInstance().getTime());
            hygieneDormitory.setCreateBy(SysUserUtils.getSysUser().getId());
            isAddSuccess = this.hygieneDormitoryService.save(hygieneDormitory);
        } else {
            hygieneDormitory.setModifyTime(Calendar.getInstance().getTime());
            hygieneDormitory.setModifyBy(SysUserUtils.getSysUser().getId());
            isAddSuccess = this.hygieneDormitoryService.updateById(hygieneDormitory);
        }
        if (isAddSuccess) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("【宿舍卫生登记】删除")
    @DeleteMapping("/deleteByIds/{ids}")
    public CommonResult<TeachingMaterialCollect> delete(@PathVariable Long[] ids) {
        List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
        boolean isDeleteSuccess = this.hygieneDormitoryService.removeByIds(idList);
        if (isDeleteSuccess) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("【宿舍卫生登记】楼栋列表接口{locationType:1楼栋、6：宿舍}")
    @GetMapping("/build/list")
    public CommonResult<List<BaseSpaceLocationVO>> buildList(@RequestParam Map<String, Object> params) {
        String locationType = (String) params.get("locationType");
        String buildName = (String) params.get("locationName");
        String locationPid = (String) params.get("locationPid");

        if (StrUtil.isEmpty(locationType)) {
            throw new ApiException("locationType空间类型，必填：1楼栋、6：宿舍");
        }

        LambdaQueryWrapper<BaseSpaceLocationVO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseSpaceLocationVO::getLocationType, locationType);
        queryWrapper.eq(BaseSpaceLocationVO::getLocationPid, locationPid);
        queryWrapper.eq(BaseSpaceLocationVO::getTenantId, SysUserUtils.getSysUser().getTenantId());
        if (StrUtil.isNotEmpty(buildName)) {
            queryWrapper.like(BaseSpaceLocationVO::getLocationName, buildName);
        }
        List<BaseSpaceLocationVO> list = this.baseSpaceLocationService.list(queryWrapper);
        return CommonResult.success(list);
    }


    /**
     * 获取建筑信息
     *
     * @return CommonResult<List < BaseSpaceLocationVO>> 建筑信息列表
     */
    @GetMapping("/build/getlist")
	public CommonResult<List<BaseSpaceLocationVO>> getBuilding() {
		// 查询条件：位置类型为 1，位置父 ID 为 0
		LambdaQueryWrapper<BaseSpaceLocationVO> queryWrapper = new LambdaQueryWrapper<BaseSpaceLocationVO>()
				.eq(BaseSpaceLocationVO::getLocationType, 1)
				.eq(BaseSpaceLocationVO::getLocationPid, 0);
		// 调用 baseSpaceLocationService.list() 方法执行查询，并将结果保存到 list 变量中
		List<BaseSpaceLocationVO> list = this.baseSpaceLocationService.list(queryWrapper);
		// 遍历 list 列表
		list.forEach(location1 -> {
			// 查询条件：位置类型为 2，位置父 ID 为当前位置的 ID
			LambdaQueryWrapper<BaseSpaceLocationVO> queryWrapper1 = new LambdaQueryWrapper<BaseSpaceLocationVO>()
					.eq(BaseSpaceLocationVO::getLocationType, 2)
					.eq(BaseSpaceLocationVO::getLocationPid, location1.getId());
			// 调用 baseSpaceLocationService.list() 方法执行查询，并将结果保存到 list1 变量中
			List<BaseSpaceLocationVO> list1 = this.baseSpaceLocationService.list(queryWrapper1);
			// 遍历 list1 列表
			list1.forEach(location2 -> {
				// 查询条件：位置类型为 6，位置父 ID 为当前位置的 ID
				LambdaQueryWrapper<BaseSpaceLocationVO> queryWrapper2 = new LambdaQueryWrapper<BaseSpaceLocationVO>()
						.eq(BaseSpaceLocationVO::getLocationType, 6)
						.eq(BaseSpaceLocationVO::getLocationPid, location2.getId());
				// 调用 baseSpaceLocationService.list() 方法执行查询，并将结果保存到 list2 变量中
				List<BaseSpaceLocationVO> list2 = this.baseSpaceLocationService.list(queryWrapper2);
				// 将 list2 设置为当前位置的子位置列表
				location2.setBaseSpaceLocationVOList(list2);
			});
			// 将 list1 设置为当前位置的子位置列表
			location1.setBaseSpaceLocationVOList(list1);
		});
		// 返回查询结果
		return CommonResult.success(list);
	}
}
